<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Giaoban extends CI_Controller
{

	public	function __construct()
	{
		parent::__construct();
		$this->load->library('pagination');
		if($this->session->userdata('user_id')){
			$this->load->helper("html");
			$this->load->model("tailieus");
			$this->load->model("giaobans");
			$this->load->model("users");			
			$this->load->model("lich");
			$this->load->model("log_model");
			date_default_timezone_set('Asia/Ho_Chi_Minh');
		}
		else{
			redirect('login');
		}
	}

	public function index($msg = null, $parameters1 = null, $parameters2 = null)
	{
		$data['list_tailieu'] = $this->tailieus->listTailieu();
		$data['list_giaoban'] = $this->giaobans->listGiaoban();
		/////////////
		$data['menu_tin'] = $this->giaobans->listGiaoban();
		$list = array();
		foreach ($data['menu_tin'] as $l){		//sap xep nhom danh sach theo giao ban cha
			if($l->id_type_giaoban != 9)
				$list[$l->cha_giaoban][] = $l;
		}
		
		$data['multi_menu_tin'] = $this->giaobans->multiGiaoban($list,0,$parameters1);						
		////////////
		$id_home = $this->giaobans->trangchu();
		if($parameters1==null) $parameters1 = $id_home; 
		if($msg != "sodotochuc")
			$data['menu'] = "giaoban".$parameters1;
		else
			$data['menu'] = "sodotochuc";
		$data['list_lich'] = $this->lich->listLich();
		$this->load->view('header_block_v1',$data);
		$this->load->view('content_sidebar_block',$data);
		switch ($msg){
			case null:
				$this->viewPageGiaoban($id_home,0);
				break;
			case 'viewall':
				$this->viewPageGiaoban($parameters1,$parameters2);
				break;
			case 'view':
				$this->viewGiaoban($parameters1,$parameters2);
				break;
			case 'viewadd':
				$this->viewAddGiaoban($parameters1);
				break;
			case 'viewedit':
				$this->viewEditGiaoban($parameters1,$parameters2);
				break;
			case 'sodotochuc':
				$this->sodo();
				break;
			default:
				$this->viewPageGiaoban($id_home,0);
				break;
		}		
		$this->load->view('footer_block');
		//$this->viewPageGiaoban($type,0);
	}
	//view
	/* public function viewAllGiaoban()
	{
		$data['allnew'] = $this->giaobans->getAllGiaoban();
		$menu['menu'] = "thongbao";
		$this->load->view('header_block_v1',$menu);
		$this->load->view('content_sidebar_block',$menu);
		$this->load->view('giaoban/viewAllGiaoban',$data);
		$this->load->view('footer_block');
	} */
	public function sodo()
	{
		$data['sodo']=$this->giaobans->top();
		$this->load->view('giaoban/viewSodo',$data);
	}
	public function viewPageGiaoban($type=1,$id=null)
	{
		if($this->input->post("date"))
			$date = $this->input->post("date");
		else
			$date = null;
		$total_row = $this->giaobans->getSoluongGiaoban($type);
		if($id==null) $id = 0;
		$data['allnew'] = $this->giaobans->getPage($date,$type,$id);
		$data['loai_tintuc'] = $this->users->getTypeTinTuc($type);
		
		$data['checkQuyen'] = $this->kiemtraQuyen($type);
		$data['typeAllow'] = ($this->giaobans->active($type,12) || $this->giaobans->active($type,13));
		$this->paging($date,$type,$total_row);
		$menu['menu'] = $type;
		$data['type'] = $type;
		$data['link'] = $this->pagination->create_links();
		$this->load->view('giaoban/viewAllGiaoban',$data);

	}
	public function viewGiaoban($type=1,$id_giaoban)
	{
		$data['new'] = $this->giaobans->getGiaoban($id_giaoban);
		$menu['menu'] = $data['new']->type_giaoban;
		$data["type"] = $type;
		$data['loai_tintuc'] = $this->users->getTypeTinTuc($type);
		$data['typeAllow'] = ($this->giaobans->active($type,12) || $this->giaobans->active($type,13));
		$data['checkQuyen'] = $this->kiemtraQuyen($type);
	
		$this->load->view('giaoban/viewGiaoban',$data);
	}
	
	public function viewAddGiaoban($type=1)
	{
		if($this->kiemtraQuyen($type)){
			$data['menu'] = $type;
			$data['loai_tintuc'] = $this->users->getTypeTinTuc($type);
			$this->load->view('giaoban/viewAddGiaoban',$data);
		}
		else
			redirect('giaoban/index/'.$type);
	}
	public function viewEditGiaoban($type=1,$id_giaoban)
	{
		if($this->kiemtraQuyen($type)){
			$data['giaoban'] = $this->giaobans->getGiaoban($id_giaoban);
			$data['loai_tintuc'] = $this->users->getTypeTinTuc($type);
			$menu['menu'] = $type;
			$data["type"] = $type;

			$this->load->view('giaoban/viewEditGiaoban',$data);

		}
		else
			redirect('giaoban/index/'.$type);
	}
	//end view
	//function
	public function download($id_thongbao)
	{
		//echo "dang download...";
		//các file upload được để trong 1 thư mục riêng
		$upload_dir = "./filedinhkemthongbao/";
		//lấy tên file cần download từ URL
		$giaoban = $this->giaobans->getGiaoban($id_thongbao);
		$name_tailieu = $giaoban->tailieu_giaoban."- Tai lieu dinh kem thong bao ".$giaoban->tieude_giaoban;
		$filename = $giaoban->tailieu_giaoban;
		$ext = explode('.', $filename);

		//thực hiện quá trình kiểm tra
		if (!is_file($upload_dir.$filename) || !is_readable($upload_dir.$filename) ) {
			///echo $upload_dir.$filename;
			echo "Loi: Ten file khong hop le hoac file khong ton tai!";
			exit(-1);
		} //end if
		$fp = fopen($upload_dir.$filename, "rb");
		//gởi header đến cho browser
		header('Content-type: application/octet-stream');
		if($ext[1] != '')
			header('Content-disposition: attachment; filename="'.$name_tailieu.'.'.$ext[1].'"');
		else
			header('Content-disposition: attachment; filename="'.$name_tailieu.'"');
		header('Content-length: ' . filesize($upload_dir.$filename));
		//đọc file và trả dữ liệu về cho browser
		fpassthru($fp);
		fclose($fp);
	}

	private function upload($userfile)
	{
		date_default_timezone_set('UTC');
		$create_date = date("YmdHis");

		$config['upload_path'] = './filedinhkemthongbao/';
		$config['allowed_types'] = '*';
		//$config['file_name'] = 'tintucs_'.$create_date;
		$config['overwrite'] = false;
		$config['max_size']	= '10048';			//<10MB
		//$config['max_width']  = '1024';			//<1024px
		//$config['max_height']  = '768';			//<768px

		$this->load->library('upload', $config);
		$this->upload->initialize($config);
		if(!$this->upload->do_upload($userfile))
		{
			$error = $this->upload->display_errors('', '');
			?>
<script type="text/javascript">	
					   alert('<?php echo $error;?>');				   
				</script>
<?php	
$upload_data = $this->upload->data($userfile);
return null;			//loi
		}
		$upload_data = $this->upload->data($userfile);

		//print_r($upload_data);

		$news_img = $upload_data['file_name'];
		return $news_img;
	}

	public function kiemtraQuyen($type){	
		//$data['typeAllow'] = ($this->giaobans->active($type,12) || $this->giaobans->active($type,13));
				
		if($this->users->checkQuyen(null,1,$type)){			//neu loai tin tuc, thong bao nam trong ds gioi han quyen
			$quyen = $this->users->getQuyen($this->session->userdata("user_id"));
			$checkQuyen = FALSE;
			if($this->session->userdata("user_id") != 12 && $this->session->userdata("user_id") != 16){
				if(count($quyen) > 0){
					foreach($quyen as $q){
						if($this->users->checkQuyen($q->id_quyen,1,$type)){
							$checkQuyen = TRUE;
							break;
						}
					}
				}
			}
			else
				$checkQuyen = TRUE;
			return $checkQuyen;
		}
		else
			return TRUE;
	}

	public function addGiaoban($type=1)
	{
		if($this->kiemtraQuyen($type)){
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
			//dieu kien form
			$this->form_validation->set_rules('tieude_tin', 'Tiêu đề giao ban', 'xss_clean|required|min_length[5]');
			$this->form_validation->set_rules('noidung_tin', 'Nội dung giao ban', 'required|min_length[5]');
			if ($this->form_validation->run() == FALSE){
				$this->index('viewadd',$type);
			}
			else {
				if($_FILES['upload_tailieu']['name'])
					$data['tailieu_giaoban'] = $this->upload('upload_tailieu');
				
				$data["tieude_giaoban"] = $this->input->post("tieude_tin");
				$data["noidung_giaoban"] = $this->input->post("noidung_tin");
				$data["type_giaoban"] = $type;
				$data["id_nguoidung"] = $this->session->userdata("user_id");
				$data["ngay_giaoban"] = date("Y-m-d H:i:s");
				//$link_menu_giaoban = $this->giaobans->getTypeGiaoban($type)->link_menu_giaoban;
				$url = base_url()."giaoban/viewall/".$type;
				$name_giaoban = $this->giaobans->getTypeGiaoban($type)->menu_name_giaoban;	
				if($this->giaobans->insertGiaoban($data)){
					if($this->log_model->saveLog(3,null,null,"Tin ".$name_giaoban." - ".$data["tieude_giaoban"]))
						echo "<script>alert('Thêm thành công');	window.location='".$url."'; </script>";
				}
				else
					echo "<script>alert('Lỗi: Không insert được!');	window.location='".$url."'; </script>";
			}
		}
		else
			redirect('giaoban/viewall/'.$type);
	}
	
	public function editGiaoban($type=1,$id_giaoban)
	{
		if($this->kiemtraQuyen($type)){
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
			//dieu kien form
			$this->form_validation->set_rules('tieude_tin', 'Tiêu đề thông báo', 'xss_clean|required|min_length[5]');
			$this->form_validation->set_rules('noidung_tin', 'Nội dung thông báo', 'required|min_length[5]');
			if ($this->form_validation->run() == FALSE){
				$this->index('viewedit',$type,$id_giaoban);
			}
			else {
				if($_FILES['upload_tailieu']['name'])
					$data['tailieu_giaoban'] = $this->upload('upload_tailieu');
					
				$data["tieude_giaoban"] = $this->input->post("tieude_tin");
				$data["noidung_giaoban"] = $this->input->post("noidung_tin");
				$data["id_nguoidung"] = $this->session->userdata("user_id");
				$data["ngay_giaoban"] = date("Y-m-d H:i:s");
				//$link_menu_giaoban = $this->giaobans->getTypeGiaoban($type)->link_menu_giaoban;
				$url = base_url()."giaoban/viewall/".$type;
				$name_giaoban = $this->giaobans->getTypeGiaoban($type)->menu_name_giaoban;
				if($this->giaobans->updateGiaoban($data,$id_giaoban)){
					if($this->log_model->saveLog(4,null,null,"Tin ".$name_giaoban." - ".$data["tieude_giaoban"]))
						echo "<script>alert('Bạn đã sửa thành công');	window.location='".$url."'; </script>";
				}
				else
					echo "<script>alert('Lỗi: Không update được!');	window.location='".$url."'; </script>";
			}
		}
		else
			redirect('giaoban/viewall/'.$type);
	}
	public function delGiaoban($type,$id_giaoban)
	{
		if($this->kiemtraQuyen($type)){
			//$link_menu_giaoban = $this->giaobans->getTypeGiaoban($type)->link_menu_giaoban;
			$url = base_url()."/giaoban/viewall/".$type;
			$name_giaoban = $this->giaobans->getTypeGiaoban($type)->menu_name_giaoban;
			$tieude_giaoban = $this->giaobans->tieude_giaoban($id_giaoban);
			if($this->giaobans->delGiaoban($id_giaoban)){
				if($this->log_model->saveLog(1,null,null,"Tin ".$name_giaoban." - ".$tieude_giaoban))
				echo "<script>alert('Bạn đã xóa thành công');	window.location='".$url."'; </script>";
			}
			else
				echo "<script>alert('Lỗi: Không del được!');	window.location='".$url."'; </script>";
		}
		else
			redirect('giaoban/viewall/'.$type);
	}
	
	function paging($date,$type,$total_row){
		$this->load->library('pagination');
		$config['base_url']=site_url("giaoban/viewall/".$type."/");
		$config['total_rows']=$total_row;
		$config['per_page']=20;
		$config['uri_segment'] = 3;
		$config['num_links'] = 1000;
		$config['full_tag_open'] = "<div class='news_pagination'>";
		$config['full_tag_close'] = '</div>';
		$config['first_link'] = 'Trang đầu';
		$config['first_tag_open'] = "<div class='news_page next'>";
		$config['first_tag_close'] = '</div>';
		$config['last_link'] = 'Trang cuối';
		$config['last_tag_open'] = "<div class='news_page next'>";
		$config['last_tag_close'] = '</div>';
		$config['next_link'] = 'Trang tiếp';
		$config['next_tag_open'] = "<div class='news_page next'>";
		$config['next_tag_close'] = '</div>';
		$config['prev_link'] = 'Trang trước';
		$config['prev_tag_open'] = "<div class='news_page next'>";
		$config['prev_tag_close'] = '</div>';
		$config['cur_tag_open'] = "<div class='news_page number curr_page'>";
		$config['cur_tag_close'] = '</div>';
		$config['num_tag_open'] = "<div class='news_page number'>";
		$config['num_tag_close'] = '</div>';
		$this->pagination->initialize($config);
	}

}